package com.uh.microservice.core.controller;

import com.uh.microservice.core.util.RandomVerificationCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Thinkpad on 2018/7/23.
 */
@Controller
@RequestMapping
public class VerificationCodeController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomVerificationCode randomValidateCode = new RandomVerificationCode();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>>   ", e);
        }
    }

    @RequestMapping("/codeVerify")
    @ResponseBody
    public String codeVerify(HttpServletRequest request, @RequestParam String verifyCode) {
        try {
            // 验证验证码
            if (verifyCode == null || verifyCode.length() <= 0) {
                return "false";
            }
            HttpSession session = request.getSession();
            String verityCodeServer = (String) session.getAttribute(RandomVerificationCode.RANDOM_CODE);
            // 验证码未初始化，赋值默认指定字符
            if (verityCodeServer == null) {
                verityCodeServer = "UN_INIT";
            }
            if (verityCodeServer.equalsIgnoreCase(verifyCode)) {
                return "true";
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "false";
    }
}
